# @Time    : 2025/01/28
# @Author  : 斯奎匝德(张仪伟)
# @File    : FileProcessor.py
# @Software: PyCharm
#
# 文件处理器
#
import os
from Utils import NewUUID,GetTimeNow
import DatabaseHelper
from flask import request, Blueprint, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from Config import configs

FileProcessor = Blueprint('FileProcessor', __name__)

@FileProcessor.errorhandler(413)
def request_entity_too_large(error):
    return jsonify({'error_code':1,'message': 'FileTooLarge'}), 413

@FileProcessor.route("/api/upload",strict_slashes=False,methods=["POST"])
def FileUpload():
    if 'file' not in request.files:
        return jsonify({'error_code':1,'message': 'NoFile'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error_code':1,'message': 'NoFile'}), 400
    if file:
        FileName = secure_filename(file.filename)
        FileNameSuffix = FileName.split(".")[-1]
        FileUUID = NewUUID()
        FileName = FileUUID + "." + FileNameSuffix
        file.save(os.path.join(configs["filePath"], FileName))
        FullPath = "/"+configs["filePath"]+"/"+FileName
        NowTime = str(GetTimeNow(False))
        res = DatabaseHelper.InsertFile(FileUUID, FullPath, NowTime)
        if res == True:
            return jsonify({'error_code': 0, 'message': 'success', 'FullPath': configs["URL"] + f"/file/{FileUUID}"}), 200
        else:
            return jsonify({'error_code': 1, 'message': str(res)}), 500


@FileProcessor.route("/file/<string:UUID>",strict_slashes=False,methods=["GET"])
def RequireFile(UUID):
    FilePath = DatabaseHelper.SearchFileByUUID(UUID)
    if isinstance(FilePath, tuple):
        return "File Error"
    else:
        FilePaths = FilePath.split("/")
        return send_from_directory(FilePaths[1],FilePaths[2])
